<script setup lang="ts">
import { reactive, ref, watch } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { useTable } from '@/hooks/web/useTableTest'

import { TableLxq } from '@/components/Lxq'

import { useForm } from '@/hooks/web/useForm'

import { required } from '@/utils/formRules'

// import { adminFaUserListApi } from '@/api/fa/user'
import { zcLoanOrderSeeApi } from '@/api/cy/Loanapply'

import { sysDictRelsApi } from '@/api/dict'

// import Edit from '../components/Edit.vue'
import { ucDeptListApi } from '@/api/uc/dept'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { zcAssetListApi } from '@/api/fa/earcon'
import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
/****************************** 变量 start ******************************/
const userInfo: any = wsCache.get('userInfo')
const data = ref<any>({})
data.value.customer_name = userInfo.default_org_name
data.value.customer_id = userInfo.default_org_id
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举

const newUserData = ref<any[]>([])

// const fileRef = ref()

// const saveLoading = ref(false)
// const d_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位

const rules = reactive({
  pasture_org_id: [required],
  breed: [required],
  breed_sub: [required],
  amount: [required],
  pasture_dept_name: [required],
  number: [required],
  loan_no: [required]
})

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object,
    default: () => null
  }
})
console.log(props.id, 'id')
/****************************** 组件参数 end ******************************/

// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcLoanOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data

      // 明细信息处理一下，加上d_id
      await methodsForm.setValues(data.value)
      const json = JSON.parse(data.value.select_json)
      Search.value = {
        breed: json.breed ? json.breed : '',
        breed_sub: json.breed_sub ? json.breed_sub : '',
        earcon_code: json.earcon_code ? json.earcon_code : '',
        asset_code: json.asset_code ? json.asset_code : ''
      }
      console.log(props.id, data.value, '11111')
    }
  } else {
    data.value.state = '1'
    data.value.selected = []
    await methodsForm.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log(res)
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
  let formData = await methodsForm.getFormData()
  await methodsForm.setValues({ ...formData, breed_sub: '' })
}

const Search = ref({
  breed: '',
  breed_sub: '',
  asset_code: '',
  earcon_code: ''
})

const getListAssetSelect = async () => {
  await getList()
}
const getListAssetReste = async () => {
  Search.value = {
    breed: '',
    breed_sub: '',
    asset_code: '',
    earcon_code: ''
  }
  await getList()
}

const onCustomer = async (value: String) => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  console.log(value, 'admin_org_id')
  if (value != data.value.pasture_org_id) {
    // data.value.pasture_org_id = Number(value)
    data.value.pasture_org_id = value
    // data.value.detailedData = []
    newTreeData.value = []
    newUserData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    data.value.pasture_user_id = ''
    data.value.pasture_user_name = ''
    DeptList(value)
  }
  await methodsForm.setValues(data.value)
  await getList()
}

let newTreeData = ref<any[]>([])
const DeptList = async (val) => {
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
  }
}

const UserList = async (value, num) => {
  data.value.pasture_dept_id = value
  data.value.pasture_dept_name = value
  newUserData.value = []
  const res = await ucOrgDeptUserListApi({ org_id: data.value.pasture_org_id, dept_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
    console.log(num, '部门')
    if (num == undefined) {
      data.value.pasture_user_id = ''
      data.value.pasture_user_name = ''
    }
  }
  console.log(data, getFormData(), '666')
}

const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}

/****************************** 明细配置 end ******************************/
const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListAdminApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } }
        // { field: 'org_id', label: '牧场ID', search: { show: true } }
      ],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '牧场用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input',
    colProps: {
      span: 12
    }
  }
]
const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  // const file = unref(fileRef) //附件
  // let fileData = file?.getData()
  // console.log(fileData, '附件')
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData, selected: data.value.selected }
}

const getListAsset = async (a) => {
  // console.log(tableObject.paramsObj, 'date')
  return zcAssetListApi({
    ...a,
    is_die: '0',
    loan_state: '1',
    pasture_org_id: data.value.pasture_org_id,
    breed: Search.value.breed ? Search.value.breed : null,
    breed_sub: Search.value.breed_sub ? Search.value.breed_sub : null,
    earcon_code: Search.value.earcon_code ? Search.value.earcon_code : null,
    asset_code: Search.value.asset_code ? Search.value.asset_code : null
  })
}
/****************************** 明细配置 start ******************************/
const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '主键',
    type: 'index',
    width: 30
  },
  {
    field: 'id',
    label: 'ID',
    width: 100
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    width: 200,
    label: '耳标编码',
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    width: 100
  },
  {
    field: 'breed_sub',
    width: 200,
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
  },
  {
    field: 'loan_state',
    label: '贷款状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('insurance_order_state', cellValue)
    }
  }
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作'
  // }
])
const { allSchemas } = useCrudSchemas(d_columns)

const { register, tableObject, methods, elTableRef } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

/****************************** 初始化 start ******************************/

watch(
  () => data,
  (value) => {
    // console.log(value.value, getFormData(), 'dataq')
    if (!value) return
    methodsForm.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => tableObject.tableList,
  (value) => {
    console.log('tableObject')
    if (!value) return
    if (data.value.checkedAll) {
      setTimeout(() => {
        if (data.value.noSelectData.length > 0) {
          // 去重
          console.log(tableObject.tableList, 'tableObject.tableList')
          console.log('有没有未被选中的')
          let newArr = tableObject.tableList.filter(
            (x) => !data.value.noSelectData.some((item) => x.id == item.id)
          )
          newArr.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
          console.log(newArr, 'newArr')
        } else {
          tableObject.tableList.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
        }
      }, 0)
    } else {
      if (data.value.selectData && data.value.selectData.length > 0) {
        data.value.selectData.forEach((row) => {
          elTableRef.value?.toggleRowSelection(row, true)
        })
      } else {
        data.value.selectData = []
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)
const getRowKey = (row) => {
  return row.id
}

const init = async () => {
  await getDictRels()
  await getMedicalOrderSee()
  // 跟新畜别
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
  if (props.currentRow) {
    console.log(props.currentRow, 'props')
    data.value.pasture_org_id = props.currentRow.pasture_org_id
      ? props.currentRow.pasture_org_id
      : ''
    data.value.checkedAll = JSON.parse(props.currentRow.select_json).checkedAll
    data.value.breed = JSON.parse(props.currentRow.select_json).breed
    data.value.breed_sub = JSON.parse(props.currentRow.select_json).breed_sub
    data.value.asset_code = JSON.parse(props.currentRow.select_json).asset_code
    data.value.earcon_code = JSON.parse(props.currentRow.select_json).earcon_code
    if (data.value.breed) {
      await breedGetSub(data.value.breed)
    }
    if (data.value.checkedAll) {
      const aaa: any = []
      JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
        let obj: any = {}
        obj.id = element
        aaa.push(obj)
      })
      data.value.noSelectData = data.value.noSelectData != undefined ? data.value.noSelectData : aaa
    } else if (props.currentRow.select_json) {
      const aaa: any = []
      if (JSON.parse(props.currentRow.select_json).selected) {
        JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
          let obj: any = {}
          obj.id = element
          aaa.push(obj)
        })
      }
      data.value.selectData = aaa
      console.log(data.value.selectData, 'data.value.selectData', aaa)
    }
    if (props.currentRow.pasture_org_id) {
      await DeptList(props.currentRow.pasture_org_id)
    }
    if (props.currentRow.pasture_dept_id) {
      await UserList(props.currentRow.pasture_dept_id, '1')
    }
    await getList()
  } else {
  }
}

init()
defineExpose({
  methods: methods,
  elFormRef,
  getFormData,
  data,
  Search
})
/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="registerForm" :data="data" />
    </ContentWrap>

    <ContentWrap title="明细数据">
      <div>
        <el-form :inline="true" :model="Search" class="demo-form-inline">
          <el-form-item label="资产编号">
            <el-input v-model="Search.asset_code" />
          </el-form-item>
          <el-form-item label="耳标编号">
            <el-input v-model="Search.earcon_code" />
          </el-form-item>
          <el-form-item label="畜别">
            <el-select v-model="Search.breed" placeholder="请选择" clearable @change="breedChange">
              <el-option
                v-for="item in dictRelsData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="品种">
            <el-select v-model="Search.breed_sub" placeholder="请选择" clearable>
              <el-option
                v-for="item in breedSubData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getListAssetSelect">查询</el-button>
            <el-button type="" @click="getListAssetReste">重置</el-button>
          </el-form-item>
        </el-form>
        <TableLxq
          v-model:pageSize="tableObject.pageSize"
          v-model:currentPage="tableObject.currentPage"
          v-model:checkedAll="data.checkedAll"
          v-model:noSelectData="data.noSelectData"
          v-model:selectData="data.selectData"
          v-model:total="tableObject.count"
          :columns="allSchemas.tableColumns"
          :data="tableObject.tableList"
          :loading="tableObject.loading"
          :border="true"
          :pagination="{
            total: tableObject.count
          }"
          :row-key="getRowKey"
          :selection="true"
          highlight-current-row
          @register="register"
        />
      </div>
    </ContentWrap>
  </div>
</template>
